from flask import Flask, request, jsonify
import mysql.connector
from flask_cors import CORS
import bcrypt

app = Flask(__name__)
CORS(app)  # 启用CORS以允许跨域请求

# 数据库连接配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': 'root',
    'database': 'zmzc'
}

@app.route('/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('name')
    password = data.get('pwd')
    user_type = data.get('userType')

    try:
        conn = mysql.connector.connect(**db_config)
        cursor = conn.cursor(dictionary=True)

        # 查询用户
        query = "SELECT * FROM login WHERE name = %s AND user_type = %s"
        cursor.execute(query, (username, user_type))
        user = cursor.fetchone()

        if user:
            # 用户存在，返回成功和用户类型
            return jsonify({"success": True, "message": "登录成功", "userType": user['user_type']})
        else:
            return jsonify({"success": False, "message": "用户名或密码错误"})

    except mysql.connector.Error as err:
        return jsonify({"success": False, "message": f"数据库错误: {err}"})

    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()

@app.route('/register', methods=['POST'])
def register():
    data = request.json
    username = data.get('name')
    email = data.get('email')
    password = data.get('pwd')
    user_type = data.get('userType')

    try:
        conn = mysql.connector.connect(**db_config)
        cursor = conn.cursor(dictionary=True)

        # 检查用户名是否已存在
        check_query = "SELECT * FROM login WHERE name = %s"
        cursor.execute(check_query, (username,))
        if cursor.fetchone():
            return jsonify({"success": False, "message": "用户名已存在"})

        # 检查邮箱是否已存在
        check_query = "SELECT * FROM login WHERE email = %s"
        cursor.execute(check_query, (email,))
        if cursor.fetchone():
            return jsonify({"success": False, "message": "邮箱已被注册"})

        # 对密码进行哈希处理
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

        # 插入新用户
        insert_query = "INSERT INTO login (name, email, pwd, user_type) VALUES (%s, %s, %s, %s)"
        cursor.execute(insert_query, (username, email, hashed_password, user_type,))
        conn.commit()

        return jsonify({"success": True, "message": "注册成功"})

    except mysql.connector.Error as err:
        return jsonify({"success": False, "message": f"数据库错误: {err}"})

    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()

if __name__ == '__main__':
    app.run(debug=True)